package com.x.wx.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.alibaba.fastjson.JSON;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.jfinal.weixin.sdk.api.ApiConfig;
import com.jfinal.weixin.sdk.api.ApiConfigKit;
import com.x.erp.model.Market;
import com.x.erp.rpc.MarketRpcService;
import com.x.framework.controller.BaseController;
import com.x.framework.controller.ResultCode;
import com.x.framework.controller.ResultModel;
import com.x.wx.model.WxAccount;
import com.x.wx.rpc.WxAccountRpcService;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.commons.CommonsMultipartFile;

import java.io.IOException;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Administrator on 2018/3/6.
 */


@RestController
@RequestMapping("/account")
public class WxAccountController extends BaseController {

	@Reference
	private WxAccountRpcService wxAccountRpcService;

	@Autowired
	private FastFileStorageClient fdfsClient;//文件服务

	@Reference
	private MarketRpcService  marketRpcService;// 商铺



	/**
	 * 微信公众号列表
	 * @param wxAccount
	 * @return
	 */
	@RequestMapping("/getWxAccountList")
	public ResultModel getWxAccountList(WxAccount wxAccount) {
		List<WxAccount>  wxAccounts= wxAccountRpcService.selectWxAccountList(wxAccount);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功", wxAccounts);
	}


	/**
	 * 新增微信公众号
	 * @param wxAccount
	 * @return
	 */
	@RequestMapping("/insertWxAccount")
	public ResultModel insertWxAccount(WxAccount wxAccount,
										@RequestParam(value = "wxLogoFile", required = true) CommonsMultipartFile wxLogoFile,
										@RequestParam(value = "wxQrCodeFile", required = true) CommonsMultipartFile wxQrCodeFile) {
		WxAccount wxAccount1 = new WxAccount();
		wxAccount1.setMarketId(wxAccount.getMarketId());
		List<WxAccount> wxAccounts= wxAccountRpcService.selectWxAccountList(wxAccount1);
		WxAccount wxAccountInfo= null;
		if(wxAccounts != null && !wxAccounts.isEmpty()){
			return new ResultModel(ResultCode.RESULT_FAIL, "已经存在该市场下的公众号请勿重复提交！");
		}
		if (wxLogoFile == null || wxLogoFile.isEmpty()) {
			return new ResultModel(ResultCode.RESULT_FAIL, "上传LOGO不能为空");
		}
		if (wxQrCodeFile == null || wxQrCodeFile.isEmpty()) {
			return new ResultModel(ResultCode.RESULT_FAIL, "上传二维码不能为空");
		}
		String logoPathUrl = null;
		String qrCodePathUrl = null;
		//上传图片
		try {
			logoPathUrl = fdfsClient.uploadFile(wxLogoFile.getInputStream(), fdfsClient.getFileExt(wxLogoFile.getOriginalFilename()));
			qrCodePathUrl = fdfsClient.uploadFile(wxQrCodeFile.getInputStream(), fdfsClient.getFileExt(wxQrCodeFile.getOriginalFilename()));
		} catch (IOException e) {
			e.printStackTrace();
			return new ResultModel(ResultCode.RESULT_FAIL, "上传失败");
		}
		if(logoPathUrl == null || logoPathUrl.equalsIgnoreCase("null")) {
			return new ResultModel(ResultCode.RESULT_FAIL, "上传失败");
		}
		if(qrCodePathUrl == null || qrCodePathUrl.equalsIgnoreCase("null")) {
			return new ResultModel(ResultCode.RESULT_FAIL, "上传失败");
		}
		wxAccount.setWxAccountState(1);
		wxAccount.setWxLogo(logoPathUrl);
		wxAccount.setWxQrCode(qrCodePathUrl);
		wxAccount.setCreateTime(this.getDate(0));
		wxAccount.setUpdateTime(this.getDate(0));
		wxAccountInfo=wxAccountRpcService.insertWxAccount(wxAccount);
		ApiConfigKit.putApiConfig(new ApiConfig(wxAccountInfo.getWxToken(), wxAccountInfo.getWxAppId(), wxAccountInfo.getWxAppSecret(), wxAccountInfo.getWxEncryptMessage(), wxAccountInfo.getWxEncodingAesKey()));
		return new ResultModel(ResultCode.RESULT_SUCCESS, "插入成功", wxAccountInfo);
	}

	/**
	 * 更新微信公众号
	 * @param wxAccount
	 * @return
	 */
	@RequestMapping("/updateWxAccount")
	public ResultModel updateWxAccount(WxAccount wxAccount,
										@RequestParam(value = "wxLogoFile", required = false) CommonsMultipartFile wxLogoFile,
										@RequestParam(value = "wxQrCodeFile", required = false) CommonsMultipartFile wxQrCodeFile) {
		if(StringUtils.isEmpty(wxAccount.getWxAccountId())){
			return new ResultModel(ResultCode.RESULT_FAIL, "公众号ID不能为空！");
		}
		if (wxAccount.getWxAccountState() == 1){
			WxAccount wxAccount1 = new WxAccount();
			wxAccount1.setMarketId(wxAccount.getMarketId());
			List<WxAccount> wxAccounts= wxAccountRpcService.selectWxAccountList(wxAccount1);
			if(wxAccounts != null && !wxAccounts.isEmpty() && JSON.toJSONString(wxAccounts).indexOf(wxAccount.getWxAccountId()) == -1){
				return new ResultModel(ResultCode.RESULT_FAIL, "抱歉！已经存在该市场下的公众号！");
			}
		}
		String logoPathUrl = null;
		String qrCodePathUrl = null;
		if (wxLogoFile != null && !wxLogoFile.isEmpty()) {
			//上传图片
			try {
				logoPathUrl = fdfsClient.uploadFile(wxLogoFile.getInputStream(), fdfsClient.getFileExt(wxLogoFile.getOriginalFilename()));
			} catch (IOException e) {
				e.printStackTrace();
				return new ResultModel(ResultCode.RESULT_FAIL, "上传失败");
			}
			if(logoPathUrl == null || logoPathUrl.equalsIgnoreCase("null")) {
				return new ResultModel(ResultCode.RESULT_FAIL, "上传失败");
			}
		}
		if (wxQrCodeFile != null && !wxQrCodeFile.isEmpty()) {
			//上传图片
			try {
				qrCodePathUrl = fdfsClient.uploadFile(wxQrCodeFile.getInputStream(), fdfsClient.getFileExt(wxQrCodeFile.getOriginalFilename()));
			} catch (IOException e) {
				e.printStackTrace();
				return new ResultModel(ResultCode.RESULT_FAIL, "上传失败");
			}
			if(qrCodePathUrl == null || qrCodePathUrl.equalsIgnoreCase("null")) {
				return new ResultModel(ResultCode.RESULT_FAIL, "上传失败");
			}
		}
		if (logoPathUrl != null &&  !logoPathUrl.equalsIgnoreCase("null")){
			wxAccount.setWxLogo(logoPathUrl);
		}
		if (qrCodePathUrl != null && !qrCodePathUrl.equalsIgnoreCase("null")){
			wxAccount.setWxQrCode(qrCodePathUrl);
		}
		wxAccount.setUpdateTime(this.getDate(0));
		wxAccountRpcService.updateWxAccount(wxAccount);
		ApiConfigKit.putApiConfig(new ApiConfig(wxAccount.getWxToken(), wxAccount.getWxAppId(), wxAccount.getWxAppSecret(), wxAccount.getWxEncryptMessage(), wxAccount.getWxEncodingAesKey()));
		return new ResultModel(ResultCode.RESULT_SUCCESS, "更新成功");
	}

	/**
	 * 冻结 解冻微信公众号
	 * @param wxAccount
	 * @return
	 */
	@RequestMapping("/freezeWxAccount")
	public ResultModel freezeWxAccount(WxAccount wxAccount) {
		if(StringUtils.isEmpty(wxAccount.getWxAccountId())){
			return new ResultModel(ResultCode.RESULT_FAIL, "公众号ID不能为空！");
		}
		wxAccount.setUpdateTime(this.getDate(0));
		wxAccountRpcService.updateWxAccount(wxAccount);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "操作成功");
	}

	/**
	 * 通过ID查询
	 * @param wxAccount
	 * @return
	 */
	@RequestMapping("/selectWxAccountById")
	public ResultModel selectWxAccountById(WxAccount wxAccount) {
		if(StringUtils.isEmpty(wxAccount.getWxAccountId())){
			return new ResultModel(ResultCode.RESULT_FAIL, "公众号ID不能为空！");
		}
		WxAccount  wxAccountInfo = wxAccountRpcService.selectWxAccountById(wxAccount);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功",wxAccountInfo);
	}

	/**
	 *  微信公众号数量
	 * @param wxAccount
	 * @return
	 */
	@RequestMapping("/selectWxAccountNum")
	public ResultModel selectWxAccountNum(WxAccount wxAccount) {
		int res = wxAccountRpcService.selectWxAccountNum(wxAccount);
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功",res);
	}

	/**
	 * 根据marketId查询公众号二维码
	 * @param marketId
	 * @return
	 */
	@RequestMapping("/selectWxQrCode")
	public ResultModel selectWxQrCode(String marketId){
		if(StringUtils.isEmpty(marketId)){
			return new ResultModel(ResultCode.RESULT_FAIL, "marketId不能为空！");
		}
		WxAccount wxAccount = new WxAccount();
		wxAccount.setMarketId(marketId);
		wxAccount.setWxAccountState(1);
		List<WxAccount> wxAccounts = wxAccountRpcService.selectWxAccountList(wxAccount);
		Map<String, Object> res = new HashMap<>();
		if(wxAccounts == null || wxAccounts.isEmpty()){
			wxAccount.setMarketId("1");
			wxAccounts = wxAccountRpcService.selectWxAccountList(wxAccount);
		}
		res.put("wxQrCode", wxAccounts.get(0).getWxQrCode());
		return new ResultModel(ResultCode.RESULT_SUCCESS, "查询成功",res);
	}

	/**
	 * 批量同步微信公众号
	 * @return
	 */
	@RequestMapping("/insertWxAccountForData")
	public ResultModel insertWxAccountForData() {
		Market market = new Market();
		market.setMarketId("1");
		WxAccount wxAccount = new WxAccount();
		wxAccount.setMarketId("1");
		List<WxAccount> wxAccountList= wxAccountRpcService.selectWxAccountList(wxAccount);
		List<Market> marketList = marketRpcService.selectMarketList(market);
		for(Market marketInfo : marketList) {
			WxAccount account = new WxAccount();
			account.setMarketId(marketInfo.getMarketId());
			List<WxAccount> accounts = wxAccountRpcService.selectWxAccountList(account);
			if(accounts == null || accounts.isEmpty()) {
				WxAccount wxAccount1 = new WxAccount();
				wxAccount1.setMarketName(marketInfo.getMarketName());
				wxAccount1.setMarketId(marketInfo.getMarketId());
				wxAccount1.setMarketShortName(marketInfo.getMarketShortName());
				wxAccount1.setWxLogo(wxAccountList.get(0).getWxLogo());
				wxAccount1.setWxQrCode(wxAccountList.get(0).getWxQrCode());
				wxAccount1.setWxAppId(wxAccountList.get(0).getWxAppId());
				wxAccount1.setWxAppSecret(wxAccountList.get(0).getWxAppSecret());
				wxAccount1.setWxToken(wxAccountList.get(0).getWxToken());
				wxAccount1.setWxEncodingAesKey(wxAccountList.get(0).getWxEncodingAesKey());
				wxAccount1.setWxEncryptMessage(wxAccountList.get(0).getWxEncryptMessage());
				wxAccount1.setWxAccountState(wxAccountList.get(0).getWxAccountState());
				wxAccount1.setCreateTime(this.getDate(0));
				wxAccount1.setUpdateTime(this.getDate(0));
				wxAccountRpcService.insertWxAccount(wxAccount1);
				ApiConfigKit.putApiConfig(new ApiConfig(wxAccount1.getWxToken(), wxAccount1.getWxAppId(), wxAccount1.getWxAppSecret(), wxAccount1.getWxEncryptMessage(), wxAccount1.getWxEncodingAesKey()));
			}
		}
		return new ResultModel(ResultCode.RESULT_SUCCESS, "插入成功");
	}



}
